package com.apes.scm.masterdata.area.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.scm.masterdata.area.repository.AreaRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.Objects;

/**
 * @Title: BusinessCircleArea
 * @Description: 商圈包含区域
 * @author: ZhengZeXian
 * @create: 2022/2/16 17:16
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = BusinessCircleArea.CONST_TABLE_NAME)
public class BusinessCircleArea extends BaseModel {

    public static final String CONST_TABLE_NAME = "mas_business_circle_area";

    @Id
    @Column(name = "id", length = 20)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "商圈包含区域")
    @Comment("编码")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "business_circle_id", referencedColumnName = "id")
    @Comment("商圈")
    private BusinessCircle businessCircle;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "area_id", referencedColumnName = "id")
    @Comment("区县")
    private Area area;

    @Transient
    private String area_id;

    @Transient
    private String area_name;

    @Transient
    private String province_name;

    @Transient
    private String city_name;

    @Transient
    private String province_id;

    public String getArea_id() {
        if (!Objects.isNull(area)){
            return area.getId();
        }else if(!Objects.isNull(area_id)){
            return area_id;
        }
        return null;
    }

    public String getArea_name() {
        if (!Objects.isNull(area)){
            return area.getName();
        }
        return null;
    }

    public String getProvince_name() {
        if (!Objects.isNull(province_id)){
            return SpringManager.getBean(AreaRepository.class).findOne(province_id).getName();
        }
        return null;
    }

    public String getCity_name() {
        if (!Objects.isNull(area) && !(area.getParent() == null || "".equals(area.getParent()))){
            Area city = SpringManager.getBean(AreaRepository.class).findOne(area.getParent());
            this.province_id = city.getParent();
            return city.getName();
        }
        return null;
    }
}
